<template>
    <!-- 供应商资质信息 -->
    <div class="e-table">
        <div class="top">
            <div class="left">
                <div>
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="aptitudeAddRow"
                        >添加</el-button
                    >
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="handleBatchDownload"
                        v-if="isBatch"
                        >批量下载</el-button
                    >
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="handleBatchDelete"
                        v-if="isBatch"
                        >批量删除</el-button
                    >
                </div>

                <div class="batchBox" @click="batchOperation">
                    <img class="batchicon" src="@/assets/piliang.png" />
                    <span class="batchfont">{{ batch }}</span>
                </div>
            </div>

            <div class="right" v-if="!newQualifications.isTableRowClass">
                <div class="squarecolor">
                    <div class="color colorAdd"></div>
                    <span>新增</span>
                </div>
                <div class="squarecolor item">
                    <div class="color colorUpdate"></div>
                    <span>修改</span>
                </div>
                <div class="squarecolor">
                    <div class="color colorDel"></div>
                    <span>删除/过期</span>
                </div>
            </div>
        </div>
        <div class="errorMsg" v-if="errorMsg.length > 0">
            <span
                style="display: block"
                v-for="(item, index) in errorMsg"
                :key="index"
            >
                {{ item }}
            </span>
        </div>
        <el-table
            :data="aptitudeTable"
            border
            style="width: 100%"
            :max-height="$store.state.tableHeight"
            @selection-change="handleDetailSelectionChange"
            @cell-click="cellClick"
            :row-class-name="tableRowClass"
            ref="table"
            class="table"
            v-sortTable="{ 'tableData': aptitudeTable, '_this': this, 'ref': 'table' }"
        >
            <el-table-column fixed label="操作" width="120">
                <template slot-scope="{ row, $index }">
                    <div class="handle">
                        <el-upload
                            style="margin: 7px 5px 0px 0px"
                            class="upload-demo"
                            :action="uploadUrl"
                            :data="{
                                bucketName,
                                relationId,
                                orgCode
                            }"
                            :before-upload="beforeAvatarUpload"
                            :accept="accept"
                            :on-success="attachOnSuccess"
                            :http-request="uploadBefore"
                            :show-file-list="false"
                            name="files"
                        >
                            <img src="@/assets/btn/commit.png" />
                        </el-upload>
                        <img
                            v-if="row.id"
                            src="@/assets/btn/downLoad.png"
                            @click="handleDownload(row)"
                            style="margin-right: 5px"
                        />
                        <img
                            v-if="row.changeType != -1"
                            src="@/assets/btn/delete.png"
                            @click="handleDelete(row, $index)"
                        />
                        <img
                            v-else
                            src="@/assets/btn/cancelDelete.png"
                            @click="revoke(row, $index)"
                        />
                        <img
                            style="margin-left: 10px"
                            src="@/assets/btn/preview.png"
                            @click="preview($index)"
                        />
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                type="index"
                width="55"
                label="序号"
            ></el-table-column>
            <el-table-column label="证书编号" width="180" show-overflow-tooltip>
                <template slot-scope="{ row }">
                    <el-input
                        :readonly="row.isShowcertNo"
                        v-model.trim="row.certNo"
                        @change="modifyState(row)"
                    ></el-input>
                </template>
            </el-table-column>
            <el-table-column label="证书类型" width="160" show-overflow-tooltip>
                <template slot-scope="{ row, $index }">
                    <el-select
                        clearable
                        v-model="row.certTypeValue"
                        @change="getCertType(row, row.certTypeValue, $index)"
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="item in certType"
                            :key="item.kvId"
                            :label="item.kvKey"
                            :value="item.kvKey"
                        >
                        </el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column
                prop="qualificationLevelName"
                label="供应商品/证书等级"
                min-width="150"
            >
                <template slot-scope="{ row, $index }">
                    <el-tooltip
                        class="item"
                        effect="dark"
                        :content="row.qualificationLevelName"
                        :disabled="!row.qualificationLevelName"
                        placement="top"
                    >
                        <span>
                            <el-input
                                v-if="row.gradeShow"
                                disabled
                                v-model="row.qualificationLevelName"
                                placeholder="请选择"
                            >
                                <i
                                    slot="suffix"
                                    class="el-icon-document-copy"
                                    @click="onSelect(row, $index)"
                                ></i>
                            </el-input>
                        </span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column
                prop="startDate"
                label="有效期开始日期"
                width="160"
            >
                <template slot-scope="{ row }">
                    <el-date-picker
                        type="date"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"
                        v-model="row.startDate"
                        style="width: 100%"
                        @change="modifyState(row)"
                    ></el-date-picker>
                </template>
            </el-table-column>
            <!-- <el-table-column  label="选择时间" width="200">
                     <template slot-scope="{ row ,$index}">

                    </template>
            </el-table-column> -->
            <el-table-column prop="endDate" label="有效期结束日期" width="260">
                <template slot-scope="{ row, $index }">
                    <div>
                        <el-select
                            style="width: 100px; margin-right: 5px"
                            v-model="row.isShow"
                            @change="changeDate(row, $index, $event)"
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="item in aptitudeTable[$index]
                                    .endDateStyle"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                        <el-date-picker
                            v-if="row.isShow != '0'"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                            v-model="row.endDate"
                            style="width: 130px"
                        ></el-date-picker>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                prop="fileName"
                label="资质附件"
                min-width="200"
                show-overflow-tooltip
            >
                <template slot-scope="{ row }">
                    {{ row.fileName }}
                </template>
            </el-table-column>
            <el-table-column
                prop="size"
                label="大小"
                min-width="120"
                show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column prop="gmtCreate" label="上传时间" width="120">
            </el-table-column>
            <el-table-column prop="founderName" label="上传人" width="120">
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import ossRequest from '@/api/oss/oss.js'
import {
    bytesToSize,
    showLoading,
    hideLoading,
    showErrorPop
} from '@/utils/common'
// 变更接口
import supplierChange from '@/api/OutsourcingartyAdmin/supplier/supplierChange'
import { selectDataClient } from '@/utils/common'
import { mapMutations } from 'vuex'
// 接口
import Supplier from '@/api/OutsourcingartyAdmin/supplier/supplier'
//import ComPagination from '@/components/pagination/pagination'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
import service from '@/utils/request'
export default {
    props: {
        // 父组件对象
        newQualifications: {
            /**
             *  billid: '', //单据id
                supplierTypeValue: [], //供应商名字id
                creditCode: '', //信用代码
                isTableRowClass: true, //是否展示class
                 isAbroadUnit: '', //是否是境外单位
             */
            type: Object,
            default: () => {
                return {}
            }
        },
        aptitudeSend: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            bucketName: 'OutsourcingartyAdmin', //模块名
            isBatch: false, //是否进入批量操作
            batch: '进入批量管理',
            checkedDetail: [], //选中的数据
            //上传的地址
            uploadUrl: '/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            relationId: '',
            pagination: {
                limit: 10, //	每页显示条数
                name: '', //合同名称
                orgName: '', //机构
                page: 1 //当前页数
            },
            totalPage: 0, //总页数
            rowIndex: '',
            certType: [],
            unWatch: '',
            errorMsg: [], //验证数组
            aptitudeTable: [], //资质信息基础数据
            gradeShow: false, //等级选择显示
            dialogVisible: false, //弹窗开关
            dialogImageUrl: '' //回显路径
        }
    },
    async created () {
        showLoading()
        hideLoading()
        //获取证书类型
        call.getCredential('供应商证书类型').then(res => {
            this.certType = res
        })
        this.qualificationList(this.newQualifications.billid) //初始化资质信息列表
    },
    computed: {
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        }
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //修改行样式
        tableRowClass ({ row }) {
            if (this.newQualifications.isTableRowClass) {
                return
            } else {
                if (row.state == -1) {
                    return 'red'
                } else if (row.state == 1) {
                    return 'green'
                } else if (row.state == 2) {
                    return 'yellow'
                }
                return ''
            }
        },
        //选择证书类型的事件
        /**
         * 6)证书类型是营业执照的时候，必须选择主营范围，弹出多选，可选择除了第一级的任意一级；
         * 7)证书类型是资质证书的时候，必须选择资质等级，弹出多选，可选择除了第一级的任意一级；
         * 8)证书类型没有选择或不是资质证书和营业执照时的时候，主营范围/资质等级禁用；
         */
        // eslint-disable-next-line no-unused-vars
        getCertType (row, certTypeValue, $index) {
            this.modifyState(row)
            // certTypeKey赋值
            this.certType.map(item => {
                if (item.kvKey == certTypeValue) {
                    this.aptitudeTable[$index].certTypeKey = item.kvValue
                }
            })
            let number = 0
            // 判断证书类型是否已经选择
            this.aptitudeTable.map(item => {
                if (item.certTypeValue == certTypeValue) {
                    number += 1
                    return
                }
            })
            if (number > 1) {
                this.errorMsg.push(certTypeValue + '已经存在')
            }
            if (certTypeValue == '营业执照') {
                // let newData = this.newQualifications.supplierTypeValue.join(',')
                /**
                 * 证书类型是营业执照的时候，必须选择供应商品，弹出多选，可选择除了第一级的任意一级；
                 *  a.供应商类型只是物资供应商的时候：供应商品为物资基础库的物资类别树；
                    b.供应商类型只是设备供应商、设备租赁商的时候：供应商品为设备基础库的设备类别树；
                    c.供应商类型是含有其他、运输单位、维修单位、加工单位中的1个或多个，或者物资供应商与设备供应商、
                    设备租赁商同时存在的时候：供应商品为物资基础库的物资类别树和设备基础库的设备类别树
                 */
                // a
                // if( newData === '11') {
                this.gradeShow = true
                // 当选择为营业执照时，默认赋值为统一社会信用代码，并且不能修改
                this.aptitudeTable[$index].certNo =
                    this.newQualifications.creditCode
                this.aptitudeTable[$index].gradeShow = true
                this.aptitudeTable[$index].isShowcertNo = true
                this.aptitudeTable[$index].isShow = '1'
                // 调用弹窗
            } else {
                // 当选择的不是营业执照的时候，证书编号可以输入
                this.aptitudeTable[$index].isShowcertNo = false
            }
            if (certTypeValue == '资质证书') {
                /**
                 * 证书类型是资质证书的时候，必须选择资质等级，弹出多选，可选择除了第一级的任意一级
                 */
                // 当选择为营业执照时，默认赋值为空，并且可以修改
                this.aptitudeTable[$index].certNo = ''
                this.aptitudeTable[$index].gradeShow = true
                this.aptitudeTable[$index].isShow = '1'
            }
        },
        onSelect (row, index) {
            if (row.certTypeValue == '营业执照') {
                let newData =
                    this.newQualifications.supplierTypeValue.join(',')
                /**
                 * 证书类型是营业执照的时候，必须选择供应商品，弹出多选，可选择除了第一级的任意一级；
                 *  a.供应商类型只是物资供应商的时候：供应商品为物资基础库的物资类别树；
                    b.供应商类型只是设备供应商、设备租赁商的时候：供应商品为设备基础库的设备类别树；
                    c.供应商类型是含有其他、运输单位、维修单位、加工单位中的1个或多个，或者物资供应商与设备供应商、
                    设备租赁商同时存在的时候：供应商品为物资基础库的物资类别树和设备基础库的设备类别树
                 */
                // a
                if (newData === '11') {
                    this.onSelectMaterial('请选择物资类别', index)
                } else if (
                    newData === '12' ||
                    newData === '13' ||
                    newData === '12,13'
                ) {
                    // b
                    this.onSelectEquipment('请选择设备类别', index)
                } else {
                    // c
                    this.onSelectAll('请选择设备类别/物资类别', index)
                }
            }
            if (row.certTypeValue == '资质证书') {
                /**
                 * 证书类型是资质证书的时候，必须选择资质等级，弹出多选，可选择除了第一级的任意一级
                 */
                // 当选择为营业执照时，默认赋值为空，并且可以修改
                this.onSelectQualifications('请选择资质等级', index)
            }
        },
        // 物资类别
        onSelectMaterial (value, index) {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/common/CategorySelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    categoryType: 1, //类别类型1：物资类型，2：设备类型，3：所有类别
                    materialCategoryId: '0', //物资类别父级id
                    estimatedMaterialLock: null, //暂估物资锁(0：否;1：是;null:全部)(物资类别)
                    materialType: 0 //物资类型(0：一般材料;1:：周转材料;null:全部)(物资类别)
                }),
                Title: value // 标题
            }).then(val => {
                // 定义空数组，存选中的name
                let newclassName = []
                let newbillId = []
                val.map(item => {
                    newclassName.push(item.className)
                    newbillId.push(item.billId)
                })
                this.aptitudeTable[index].qualificationLevelId = val[0].billId
                this.aptitudeTable[index].qualificationLevelName =
                    newclassName.join(',')
            })
        },
        // 设备
        onSelectEquipment (value, index) {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/common/CategorySelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    categoryType: 2, //类别类型1：物资类型，2：设备类型，3：所有类别
                    equipmentCategoryId: '00000', //设备类别父级id
                    isUpdate: false //true 基础库调用 false 其他地方调用(设备类别)
                }),
                Title: value // 标题
            }).then(val => {
                // 定义空数组，存选中的name
                let newclassName = []
                let newbillId = []
                val.map(item => {
                    newclassName.push(item.className)
                    newbillId.push(item.billId)
                })
                this.aptitudeTable[index].qualificationLevelId = val[0].billId
                this.aptitudeTable[index].qualificationLevelName =
                    newclassName.join(',')
            })
        },
        // 全部
        onSelectAll (value, index) {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/common/CategorySelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    categoryType: 3, //类别类型1：物资类型，2：设备类型，3：所有类别
                    materialCategoryId: '0', //物资类别父级id
                    equipmentCategoryId: '00000', //设备类别父级id
                    isUpdate: false, //true 基础库调用 false 其他地方调用(设备类别)
                    estimatedMaterialLock: null, //暂估物资锁(0：否;1：是;null:全部)(物资类别)
                    materialType: null //物资类型(0：一般材料;1:：周转材料;null:全部)(物资类别)
                }),
                Title: value // 标题
            }).then(val => {
                // 定义空数组，存选中的name
                let newclassName = []
                let newbillId = []
                val.map(item => {
                    newclassName.push(item.className)
                    newbillId.push(item.billId)
                })
                this.aptitudeTable[index].qualificationLevelId =
                    newbillId.join(',')
                this.aptitudeTable[index].qualificationLevelName =
                    newclassName.join(',')
            })
        },
        // 资质等级
        onSelectQualifications (value, index) {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/config/kv/getDicValueTree', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    dicName: '资质等级',
                    parentId: '0'
                }),
                Title: value // 标题
            }).then(val => {
                // 定义空数组，存选中的name
                let newclassName = []
                let newbillId = []
                val.map(item => {
                    newclassName.push(item.kvValue)
                    newbillId.push(item.kvId)
                })
                this.aptitudeTable[index].qualificationLevelId =
                    newbillId.join(',')
                this.aptitudeTable[index].qualificationLevelName =
                    newclassName.join(',')
            })
        },

        //是否批量管理
        batchOperation () {
            this.isBatch = !this.isBatch
            if (this.isBatch) {
                this.batch = '退出批量管理'
                this.$refs.table.clearSelection()
            } else {
                this.batch = '进入批量管理'
            }
        },
        cellClick (row) {
            //是第几行
            this.rowIndex = this.aptitudeTable.findIndex(x => x === row)
        },
        //资质信息添加一行
        aptitudeAddRow () {
            if (
                this.newQualifications.supplierTypeValue.length > 0 &&
                this.newQualifications.creditCode
            ) {
                let obj = {
                    certNo: '', //证书编号
                    certTypeKey: '', //	证书类型（字典）
                    certTypeValue: '', //证书类型（字典）
                    endDate: '', //结束日期
                    fileName: '', //文件名
                    founderId: '', //文件下载路经
                    founderName: '', //文件大小
                    gmtCreate: '', //上传人
                    id: '', //录入人Id
                    outerBillId: this.billId, //外包方id
                    outerName: this.outerNames, //外包方名字
                    outerTypeKey: '', //明细Id
                    outerTypeValue: '', //外包方Id
                    qualificationLevelId: '', //资质等级id
                    qualificationLevelName: '', //资质等级名称
                    relationId: '', //关联ID
                    startDate: '', //开始日期
                    isShow: '1', //是否展示时间组件
                    endDateStyle: [
                        { name: '时间格式', id: '1' },
                        { name: '永久', id: '0' }
                    ], //选择时间的数据
                    changeType: 1, //前端操作字段
                    filePath: '', //文件下载路经
                    fileSize: 0, //文件大小
                    fileUploaderId: '', //上传人id
                    fileUploaderName: '', //上传人名字
                    size: 0, //文件大小
                    state: '1', //变更状态
                    isShowcertNo: false, //是否禁用证书编号
                    newState: '1', //当期新增字段，判断是当前次新增的数据还是从后端请求回来的数据
                }
                this.aptitudeTable.push(obj)
            } else {
                showErrorPop('必须先填写信用代码和供应商类型')
            }
        },
        //选中的行
        handleDetailSelectionChange (selection) {
            this.checkedDetail = selection
        },
        //删除一行
        handleDelete (row, $index) {
            if (this.newQualifications.isTableRowClass) {
                if (row.id) {
                    this.clientPop(
                        'info',
                        '确定要删除吗？数据删除后不可恢复，请谨慎操作',
                        this.callback(row)
                    )
                } else {
                    this.aptitudeTable.splice($index, 1)
                }
            } else {
                this.clientPop(
                    'info',
                    '确定要删除吗？数据删除后不可恢复，请谨慎操作',
                    this.callbacks(row, $index)
                )
            }
        },
        // 编辑删除回调
        callback (row) {
            return () => {
                row.changeType = -1
                this.$emit('getAptitudeData', row)
            }
        },
        // 变更删除回调
        callbacks (row, index) {
            return () => {
                if (!row.newState) {
                    this.aptitudeTable[index].changeType = -1
                    this.aptitudeTable[index].state = -1
                } else {
                    this.aptitudeTable.splice(index, 1)
                }
            }
        },
        // 撤销
        revoke (row, index) {
            if (row.sourceId) {
                this.aptitudeTable[index].state = this.oldDate[index].state
            } else {
                this.aptitudeTable[index].state = 1
            }
            this.aptitudeTable[index].changeType = 0
        },
        //批量删除
        handleBatchDelete () {
            const length = this.checkedDetail.length
            this.clientPop(
                'info',
                `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                this.delete
            )
        },
        delete () {
            this.checkedDetail.forEach(item => {
                if (item.outerBillId && item.state != -1) {
                    const newArr = []
                    newArr.push(item)
                    newArr.forEach(item => {
                        this.$set(item, 'changeState', -1)
                        this.$set(item, 'state', -1)
                    })
                    this.$refs.table.clearSelection()
                } else {
                    const localArr = []
                    localArr.push(item)
                    for (let i = this.aptitudeTable.length; i > 0; i--) {
                        for (let j = 0; j < localArr.length; j++) {
                            if (this.aptitudeTable[i - 1] === localArr[j]) {
                                this.aptitudeTable.splice(i - 1, 1)
                            }
                        }
                    }
                    this.$refs.table.clearSelection()
                }
            })
        },
        //下载某一行
        //批量下载
        handleBatchDownload () {},
        //文件大小
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        //上传成功
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        //获取上传成功的对象
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    res.map(x => {
                        x.fileName = x.objectName
                        x.size = x.objectSize
                        x.founderName = x.ossBucketName
                        return scrollX
                    })
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'dialogImage',
                        res[0].objectPath
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'fileName',
                        res[0].objectName
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'fileSize',
                        res[0].objectSize
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'size',
                        res[0].objectSize
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'founderName',
                        res[0].ossBucketName
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'relationId',
                        this.relationId
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'gmtCreate',
                        res[0].gmtCreate.slice(0, res[0].gmtCreate.indexOf(' '))
                    )
                })
        },
        bytesToSize (byte) {
            return bytesToSize(byte)
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBefore (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccess()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },
        //保存
        preserve () {
            // 首先将changeTy为-1的过滤掉
            let data = this.aptitudeTable.filter(item => {
                return item.changeType != -1
            })
            this.errorMsg = []
            let isContain = [] //定义证书类型临时数组
            let newData = [] //定义不包含数据
            // 将证书类型存入临时数组
            isContain = data.map(item => {
                return item.certTypeKey
            })
            // 判断哪些字段重复
            var result = [] //不重复字段
            var result2 = [] //重复字段
            for (var i = 0; i < isContain.length; i++) {
                if (result.indexOf(isContain[i]) == -1) {
                    result.push(isContain[i])
                } else {
                    if (result2.indexOf(isContain[i]) == -1) {
                        result2.push(isContain[i])
                    }
                }
            }
            // 判断你是否重复，如果重复不进行下一步判断
            if (result2.length < 1) {
                // 去重
                let isContains = [...new Set(isContain)]
                /**
                 * 12)勾选了境外单位或供应商类型只有其他的时候，则必须上传营业执照、法人证件，其他证书类型可传可不传
                 */
                if (
                    this.newQualifications.supplierTypeValue == '6' ||
                    this.newQualifications.isAbroadUnit == 1
                ) {
                    let oldArry = ['0', '4'] // 营业执照、法人证件
                    // 检验哪些不包含在该数组
                    newData = oldArry.filter(item => {
                        if (!isContains.includes(item)) {
                            return item
                        }
                    })
                } else {
                    let oldArry = ['0', '1', '2', '3', '4'] // 营业执照、资质证书、合格供方调查表、企业资信信息、法人证件
                    // 检验哪些不包含在该数组
                    newData = oldArry.filter(item => {
                        if (!isContains.includes(item)) {
                            return item
                        }
                    })
                }
                if (newData.length < 1) {
                    //修改chengeType状态为修改状态
                    this.aptitudeTable.map(item => {
                        if (item.id) {
                            item.changeType = 2
                            return item
                        }
                    })
                    // 验证是否有数据
                    let isStr = false
                    this.aptitudeTable.forEach((item, index) => {
                        let str1 = `请完善第 ${index + 1} 行的`
                        if (
                            item.certTypeValue === '' ||
                            item.certTypeValue === null
                        ) {
                            let str = '证书类型,'
                            isStr = true
                            str1 += str
                        }
                        if (item.startDate === '' || item.startDate === null) {
                            let str = '开始时间,'
                            isStr = true
                            str1 += str
                        }
                        if (item.endDate === '' || item.endDate === null) {
                            let str = '结束时间,'
                            isStr = true
                            str1 += str
                        }
                        if (
                            (item.certTypeKey == '0' ||
                                item.certTypeKey == '1') &&
                            (item.qualificationLevelName === '' ||
                                item.qualificationLevelName === null)
                        ) {
                            let str = '供应商品/证书等级,'
                            isStr = true
                            str1 += str
                        }
                        if (item.fileName === '' || item.fileName === null) {
                            let str = '资质附件,'
                            isStr = true
                            str1 += str
                        }
                        if (
                            Date.parse(item.startDate) >=
                            Date.parse(item.endDate)
                        ) {
                            let str = '结束时间必须大于开始时间'
                            isStr = true
                            str1 += str
                        }
                        if (item.certNo === '' || item.certNo === null) {
                            isStr = true
                            let str = '证书编号,'
                            str1 += str
                        } else {
                            if (!/^[0-9A-Z]+$/.test(item.certNo)) {
                                let str = '证书编号格式不正确！'
                                isStr = true
                                str1 += str
                            }
                        }
                        if (isStr) {
                            this.errorMsg.push(str1)
                        }
                    })
                    if (this.errorMsg.length > 0) {
                        this.$emit('update:aptitudeSend', false)
                        this.$emit('setError', 'aptitude')
                        return
                    } else {
                        // 将数据传给父组件
                        this.aptitudeTable.map(item => {
                            item.outerBillId = this.newQualifications.billid
                        })
                        this.$emit('update:aptitudeSend', true)
                        this.$emit('update:aptitudeTables', this.aptitudeTable)
                    }
                } else {
                    let keyData = []
                    this.certType.map(item => {
                        newData.map(newItem => {
                            if (item.kvValue == newItem)
                                keyData.push(item.kvKey)
                        })
                    })
                    this.$emit('update:aptitudeSend', false)
                    this.$emit('setError', 'aptitude')
                    this.errorMsg.push(`${keyData}` + '未填写')
                }
            } else {
                result2.map(item => {
                    this.certType.map(newItem => {
                        if (item == newItem.kvValue) {
                            this.errorMsg.push(`${newItem.kvKey}'重复'`)
                        }
                    })
                })
            }
        },

        // 资质信息列表
        async qualificationList (val) {
            // 如果有isTableRowClass，则调编辑页面的资质接口，否则调变更页面的资质接口
            let data = []
            if (this.newQualifications.isTableRowClass) {
                data = await Supplier.supplierQualificationsList(val)
                // 如果有数据。则赋值给列表数据
                if (data.length > 0) {
                    this.aptitudeTable = data
                }
            } else {
                // 变更资质信息列表
                data = await supplierChange.supplierQualificationsChangeList(
                    val
                )
                this.aptitudeTable = data
            }
            // 如果有数据。则赋值给列表数据
            if (data.length > 0) {
                // 处理有效结束时间的回显
                this.aptitudeTable = data.map(item => {
                    if (item.certTypeKey == '0') {
                        item.isShowcertNo = true
                    }
                    if (new Date(item.endDate).getFullYear() == 9999) {
                        item.isShow = '0'
                    } else {
                        item.isShow = '1'
                    }
                    item.endDateStyle = [
                        {
                            name: '永久',
                            id: '0'
                        },
                        {
                            name: '时间格式',
                            id: '1'
                        }
                    ]
                    return item
                })
                this.oldDate = JSON.parse(JSON.stringify(this.aptitudeTable))
            }
        },
        // 获取用户选择的是否是永久，
        changeDate (row, index, val) {
            // 此操作是为了及时更新页面，将原数据删除之后再重新赋值进去，就会触发页面的双向绑定
            this.aptitudeTable.splice(index, 1, row)
            this.modifyState(row)
            this.$nextTick(() => {
                if (val == 0) {
                    this.aptitudeTable[index].endDate = '9999-12-30'
                } else {
                    this.aptitudeTable[index].endDate = new Date()
                }
            })
        },
        // 修改样式
        modifyState (row) {
            if (this.oldDate) {
                this.oldDate.map(item => {
                    if (item.id == row.id && row.sourceId) {
                        // if( !this.isObjectValueEqual(item, row)) {
                        this.aptitudeTable.map(items => {
                            if (items.id == row.id) {
                                return (items.state = 2)
                            }
                        })
                        // }
                    }
                })
            }
        },
        //预览附件
        preview (val) {
            if (this.aptitudeTable[val].dialogImage) {
                window.open(this.aptitudeTable[val].dialogImage)
            } else {
                this.clientPop('err', '请先上传附件')
            }
        },
        //下载某一行
        async handleDownload (obj) {
            showLoading()
            const url = obj.dialogImage
            const fileNameFull = obj.fileName
            const fileExt = fileNameFull.split('.').pop()
            if (
                ['jpg', 'jpeg', 'gif', 'png', 'bmp'].indexOf(
                    fileExt.toLowerCase()
                ) === -1
            ) {
                const { httpGetFile } = service
                const data = await httpGetFile({ url })
                const blob = new Blob([data])
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = function (e) {
                    this.autoClick({
                        fileName: fileNameFull,
                        url: e.target.result
                    })
                }.bind(this)
            } else {
                this.downloadIamge(url, fileNameFull)
            }
            hideLoading()
        },
        downloadIamge (imgsrc, fileName) {
            //下载图片地址和图片名
            var image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function () {
                const canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                const context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                const _dataURL = canvas.toDataURL('image/png') //得到图片的base64编码数据

                const blob_ = this.dataURLtoBlob(_dataURL) // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会

                const url = {
                    name: fileName || '图片.png', // 图片名称不需要加.png后缀名
                    src: blob_
                }

                if (window.navigator.msSaveOrOpenBlob) {
                    // if browser is IE
                    navigator.msSaveBlob(url.src, url.name) //filename文件名包括扩展名，下载路径为浏览器默认路径
                } else {
                    this.autoClick({
                        fileName: url.name,
                        url: window.URL.createObjectURL(url.src)
                    })
                }
            }.bind(this)
            image.src = imgsrc
        },
        dataURLtoBlob (dataurl) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = window.atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        },
        autoClick ({ fileName, url }) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = url
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
        }
    }
}
</script>

<style lang="scss" scoped>
.handle {
    display: flex;
    align-items: center;
    text-align: left;
    div {
        cursor: pointer;
    }
    .download {
        font-size: 23px;
        font-weight: bold;
        color: rgb(122, 168, 24);
    }
}
</style>
